<template>
  <nav-bar title="随你运" :back="false">
    <template #left>
      <div class="news_count" @click="goNews">
        <svg-icon name="news-white" class="iconfont"></svg-icon>
        <span class="count" v-show="newsCount > 0">{{ newsCount > 99 ? '99+' : newsCount }}</span>
      </div>
    </template>
  </nav-bar>
  <div class="main">
    <div class="address">
      <div class="address_left">
        <div class="icon">装</div>
        <div class="line"></div>
        <div class="icon out_icon">卸</div>
      </div>
      <div class="address_right">
        <div class="item" @click="toAddressInfo('start')">
          <div class="item_top">
            装货地
            <van-icon name="arrow" class="arrow" />
          </div>
          <div class="filed">
            {{ start }}
            <span v-show="!start">请选择装货地址</span>
          </div>
        </div>
        <div class="item item_out" @click="toAddressInfo('end')">
          <div class="item_top">
            卸货地
            <van-icon name="arrow" class="arrow" />
          </div>
          <div class="filed">
            {{ end }}
            <span v-show="!end">请选择卸货地址</span>
          </div>
        </div>
      </div>
    </div>
    <van-form class="form">
      <van-field
        v-model="startDate"
        readonly
        right-icon="arrow"
        placeholder="请选择装货时间"
        @click="startShowPopup = true"
      />
      <van-field
        v-model="endDate"
        readonly
        right-icon="arrow"
        placeholder="请选择卸货时间"
        @click="endShowPopup = true"
      />

      <van-popup v-model:show="startShowPopup" position="bottom">
        <van-datetime-picker
          v-model="currentDate"
          type="datetime"
          title="选择装货时间"
          :min-date="minDate"
          :max-date="maxDate"
          @confirm="changeStartTime"
          @cancel="startShowPopup = false"
          :formatter="formatter"
        />
      </van-popup>
      <van-popup v-model:show="endShowPopup" position="bottom">
        <van-datetime-picker
          v-model="currentDate"
          type="datetime"
          title="选择卸货时间"
          :min-date="endMinDate"
          :max-date="endMaxDate"
          @confirm="changeEndTime"
          @cancel="endShowPopup = false"
          :formatter="formatter"
        />
      </van-popup>
    </van-form>
    <van-button type="primary" class="button" :disabled="isClick" @click="goDeliveryInfo">去下单</van-button>
  </div>
</template>

<script lang="ts">
import navBar from '@/components/NavBar.vue'
import { reactive, toRefs, onActivated, unref, ref, watch } from 'vue'
import { onBeforeRouteLeave, useRouter, useRoute } from 'vue-router'
import moment from 'moment'
import { filterFullAddress } from '@/utils/filter'
import { deepClone } from '@/utils/utils'
import store from '@/store/index'
import { Toast } from 'vant'

export default {
  name: 'Delivery',
  components: {
    navBar
  },
  setup() {
    const currentDate = new Date(new Date().getTime() + 1000 * 60 * 2)

    const initData = {
      startInfo: {} as any,
      endInfo: {},
      start: '',
      end: '',
      startDate: '',
      endDate: '',
      startShowPopup: false,
      endShowPopup: false,
      isClick: true,
      currentDate: currentDate,
      endMinDate: currentDate,
      endMaxDate: new Date(2025, 10, 1)
    }

    const formatter = (type: string, val: number) => {
      //"year" | "month" | "day" | "hour" | "minute"
      switch (type) {
        case 'year':
          return `${val}年`
        case 'month':
          return `${val}月`
        case 'day':
          return `${val}日`
        case 'hour':
          return `${val}时`
        case 'minute':
          return `${val}分`
        default:
          return val
      }
    }

    const state = reactive({ ...initData })
    const newsCount = ref<number>(0)
    const route = useRoute(),
      router = useRouter()
    const changeStartTime = (value: any) => {
      state.startDate = moment(value).format('YYYY-MM-DD HH:mm:ss')
      state.startShowPopup = false
      state.endMinDate = value
      state.endMaxDate = new Date(value.getTime() + 48 * 60 * 60 * 1000)
    }
    const changeEndTime = (value: any) => {
      if (!state.startDate) {
        Toast('请先选择开始装货时间')
        return
      }
      state.endDate = moment(value).format('YYYY-MM-DD HH:mm:ss')
      state.endShowPopup = false
    }
    //去地址信息填写页面
    const toAddressInfo = (type: string) => {
      let adderssInfo = '{}'
      if (type === 'start') {
        adderssInfo = JSON.stringify(unref(state.startInfo))
      } else {
        adderssInfo = JSON.stringify(unref(state.endInfo))
      }

      router.push({
        name: 'AddressInfo',
        params: { type, adderssInfo }
      })
    }

    //去完善发货信息
    const goDeliveryInfo = () => {
      const time = new Date(state.endDate).getTime() - new Date(state.startDate).getTime()
      if (time < 0) {
        Toast('装货时间不能大于卸货时间')
        return
      }
      if (time > 1000 * 60 * 60 * 48) {
        Toast('装货时间和卸货时间间隔不能大于3天')
        return
      }
      router.push({
        name: 'DeliveryInfo',
        params: { baseInfo: JSON.stringify(unref(state)) }
      })
    }
    watch(
      [() => state.start, () => state.end, () => state.startDate, () => state.endDate],
      ([start, end, startDate, endDate]) => {
        if (start && end && startDate && endDate) {
          state.isClick = false
        } else {
          state.isClick = true
        }
      }
    )

    // 获取通知未读列表
    const handleGetNotice = async (): Promise<void> => {
      const result = await store.dispatch('newsCenter/handleGetNotice', { type: 1, status: 0 })
      const data = result.rows.filter((item: any) => {
        return item.noticeType !== 3
      })
      if (data.length > 0) {
        newsCount.value = data.length
      }
    }

    const goNews = () => {
      router.push({ name: 'NewsCenter' })
    }

    onActivated(() => {
      handleGetNotice()
      if (route.params.addressInfo) {
        const adderssInfo = JSON.parse(route.params.addressInfo as string)
        if (adderssInfo.type === 'start') {
          state.startInfo = adderssInfo
          state.start = `${filterFullAddress(deepClone(adderssInfo.addressArr))}${adderssInfo.detailAddress}`
        } else {
          state.endInfo = adderssInfo
          state.end = `${filterFullAddress(deepClone(adderssInfo.addressArr))}${adderssInfo.detailAddress}`
        }
      }
    })

    onBeforeRouteLeave((to, from, next) => {
      if (to.name !== 'AddressInfo' && to.name !== 'DeliveryInfo') {
        store.commit('cachedView/clearCachedItem', from)
      }
      next()
    })

    return {
      ...toRefs(state),
      newsCount,
      minDate: currentDate,
      maxDate: new Date(2025, 10, 1),
      changeStartTime,
      changeEndTime,
      toAddressInfo,
      goDeliveryInfo,
      formatter,
      goNews
    }
  }
}
</script>

<style lang="scss" scoped>
@import '@/style/variables.scss';
@import '@/style/mixins.scss';
.main {
  width: 100%;
  min-height: $main-min-height;
  background: $background-color-base;
  padding: 15px 12px;
  box-sizing: border-box;
  position: relative;
}
.news_count {
  width: 22px;
  height: 22px;
  position: relative;
  > .iconfont {
    width: 22px;
    height: 22px;
  }
  > .count {
    min-width: 16px;
    padding: 0 3px;
    box-sizing: border-box;
    height: 16px;
    text-align: center;
    line-height: 16px;
    background: #ff6459;
    color: #fff;
    font-size: 10px;
    border-radius: 50%;
    position: absolute;
    top: -3px;
    left: 13px;
  }
}
.address {
  padding: 16px 10px 0 10px;
  box-sizing: border-box;
  background: #ffffff;
  box-shadow: 0px 6px 14px 0px rgba(221, 221, 221, 0.15);
  border-radius: 10px;
  display: flex;
  justify-self: start;
  margin-bottom: 10px;
  &_left {
    @include flex-column-horizontal;
    font-size: 12px;
    color: #fff;
    > .icon {
      width: 17px;
      height: 17px;
      line-height: 17px;
      text-align: center;
      background: $color-primary;
      border-radius: 6px;
      margin-right: 3;
    }
    > .out_icon {
      margin-left: 3;
      background: $orange;
    }
    > .line {
      width: 0px;
      height: 42px;
      border-right: 1px dashed $border-color-light;
      margin: 3px;
    }
  }
  &_right {
    width: 100%;
    margin-left: 10px;
    > .item {
      width: 100%;
      .item_top {
        width: 100%;
        @include flex-space-between-vertical;
        .arrow {
          color: $color-text-regular;
        }
      }
      .filed {
        width: 100%;
        height: 34px;
        padding: 6px 0;
        box-sizing: border-box;
        position: relative;
        font-size: 12px;
        @include ellipsis;
        &::after {
          @include px-1;
        }
        > span {
          font-size: 12px;
          color: $color-text-secondary;
        }
      }
    }
    > .item_out {
      margin-top: 15px;
      .filed::after {
        display: none;
      }
    }
  }
}
.form {
  box-shadow: 0px 6px 14px 0px rgba(221, 221, 221, 0.15);
  border-radius: 10px;
  overflow: hidden;
}
.button {
  width: 325px;
  height: 48px;
  position: absolute;
  left: 24px;
  bottom: 40px;
  border-radius: 24px;
}
::v-deep(.van-cell) {
  padding: 10px 10px 10px 15px;
  height: 50px;
}
::v-deep(.van-field__control::-webkit-input-placeholder) {
  font-size: 14px;
  color: $color-text-secondary;
}
::v-deep(.van-icon) {
  color: $color-text-regular;
  font-size: 12px;
}
</style>
